import React, { useState, useEffect } from 'react';
import { Layout, Button, Spin, message } from 'antd';
import { EditOutlined, ProjectOutlined } from '@ant-design/icons';
import axios from 'axios';
import { API_BASE_URL } from '../config';
import TemplateFeature from './TemplateFeature';
import TemplateParameter from './TemplateParameter';
import ProcessFlowChart from './ProcessFlowChart';

// 模板详情的CSS样式
const customStyles = `
  .template-detail-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #f0f2f5;
    overflow: auto;
  }
  
  .template-detail-header {
    padding: 0;
    background: #fff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    z-index: 1;
  }
  
  .template-detail-tabs {
    display: flex;
    align-items: center;
    padding: 0 16px;
    border-bottom: 1px solid #e8e8e8;
  }
  
  .template-detail-tab {
    padding: 16px 0;
    margin-right: 24px;
    cursor: pointer;
    position: relative;
    font-size: 14px;
  }
  
  .template-detail-tab.active {
    color: #1766a3;
    font-weight: bold;
  }
  
  .template-detail-tab.active::after {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    height: 2px;
    background: #1766a3;
  }
  
  .template-detail-content {
    padding: 24px;
    background: #fff;
    margin: 16px;
    flex: 1;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    overflow: auto;
  }
  
  .template-detail-item {
    display: flex;
    margin-bottom: 16px;
  }
  
  .template-detail-label {
    color: #666;
    text-align: right;
    padding-right: 16px;
    font-weight: 500;
    flex: 0 0 120px;
  }
  
  .template-detail-value {
    color: #333;
    flex: 1;
  }
  
  .template-detail-actions {
    display: flex;
    justify-content: flex-end;
    margin: 16px;
  }
  
  /* 响应式样式 */
  @media (max-width: 576px) {
    .template-detail-content {
      padding: 16px;
      margin: 8px;
    }
    
    .template-detail-label {
      flex: 0 0 100px;
    }
    
    .template-detail-tab {
      padding: 12px 0;
      margin-right: 16px;
    }
  }
`;

const { Content } = Layout;

// 模板详情组件
const ProcessTemplateDetail = ({ templateId }) => {
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [templateDetail, setTemplateDetail] = useState(null);
  const [activeTab, setActiveTab] = useState('detail');
  const [isMobile, setIsMobile] = useState(false);
  const [flowChartVisible, setFlowChartVisible] = useState(false);

  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 576);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 获取模板详情
  useEffect(() => {
    const fetchTemplateDetail = async () => {
      if (!templateId) return;
      
      setLoading(true);
      try {
        const response = await axios.get(`${API_BASE_URL}/api/process_template_info/${templateId}`);
        
        if (response.data && response.data.code === 200) {
          console.log('模板详情数据:', response.data.data);
          setTemplateDetail(response.data.data);
        } else {
          message.error('获取模板详情失败: ' + (response.data.message || '未知错误'));
        }
      } catch (error) {
        console.error('获取模板详情错误:', error);
        message.error('获取模板详情失败: ' + (error.message || '网络错误'));
      } finally {
        setLoading(false);
      }
    };

    fetchTemplateDetail();
  }, [templateId]);

  // 处理选项卡切换
  const handleTabChange = (tab) => {
    setActiveTab(tab);
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '-';
    try {
      const date = new Date(dateString);
      if (!isNaN(date.getTime())) {
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        }).replace(/\//g, '-');
      }
      return dateString;
    } catch (error) {
      console.error('日期格式化错误:', error);
      return dateString || '-';
    }
  };

  // 状态映射
  const getStatusText = (status) => {
    const statusMap = {
      'active': '生效',
      'inactive': '未生效',
      'draft': '草稿',
      'archived': '归档'
    };
    return statusMap[status] || status || '-';
  };

  // 渲染模板详情内容
  const renderTemplateDetail = () => {
    if (!templateDetail) {
      return (
        <div style={{ textAlign: 'center', padding: '30px 0' }}>
          {loading ? '正在加载...' : '暂无数据'}
        </div>
      );
    }
    
    return (
      <div>
        <div className="template-detail-item">
          <div className="template-detail-label">编码:</div>
          <div className="template-detail-value">{templateDetail.code || '-'}</div>
        </div>
        
        <div className="template-detail-item">
          <div className="template-detail-label">名称:</div>
          <div className="template-detail-value">{templateDetail.name || '-'}</div>
        </div>
        
        <div className="template-detail-item">
          <div className="template-detail-label">当前版本:</div>
          <div className="template-detail-value">{templateDetail.current_version || '-'}</div>
        </div>
        
        <div className="template-detail-item">
          <div className="template-detail-label">状态:</div>
          <div className="template-detail-value">{getStatusText(templateDetail.status)}</div>
        </div>
        
        <div className="template-detail-item">
          <div className="template-detail-label">适用产品类型:</div>
          <div className="template-detail-value">{templateDetail.applicable_product_type || '-'}</div>
        </div>
        
        <div className="template-detail-item">
          <div className="template-detail-label">描述:</div>
          <div className="template-detail-value">{templateDetail.description || '-'}</div>
        </div>
        
        <div className="template-detail-item">
          <div className="template-detail-label">创建时间:</div>
          <div className="template-detail-value">{formatDate(templateDetail.create_time)}</div>
        </div>
        
        <div className="template-detail-item">
          <div className="template-detail-label">更新时间:</div>
          <div className="template-detail-value">{formatDate(templateDetail.update_time)}</div>
        </div>
      </div>
    );
  };

  // 打开流程图
  const handleOpenFlowChart = () => {
    console.log('打开工艺模板流程图，templateId:', templateId);
    setFlowChartVisible(true);
  };

  // 关闭流程图
  const handleCloseFlowChart = () => {
    setFlowChartVisible(false);
  };

  return (
    <div className="template-detail-container">
      <style dangerouslySetInnerHTML={{ __html: customStyles }} />
      
      <div className="template-detail-header">
        <div className="template-detail-tabs">
          <div 
            className={`template-detail-tab ${activeTab === 'detail' ? 'active' : ''}`}
            onClick={() => handleTabChange('detail')}
          >
            模板详情
          </div>
          <div 
            className={`template-detail-tab ${activeTab === 'feature' ? 'active' : ''}`}
            onClick={() => handleTabChange('feature')}
          >
            模板特征
          </div>
          <div 
            className={`template-detail-tab ${activeTab === 'parameter' ? 'active' : ''}`}
            onClick={() => handleTabChange('parameter')}
          >
            模板参数
          </div>
          <div style={{ flex: 1 }}></div>
          <Button 
            type="primary"
            icon={<ProjectOutlined />}
            onClick={handleOpenFlowChart}
            style={{ marginTop: 8, marginBottom: 8 }}
          >
            工艺流程图
          </Button>
        </div>
      </div>
      
      <Spin spinning={loading && activeTab === 'detail'}>
        <div className="template-detail-content">
          {activeTab === 'detail' && renderTemplateDetail()}
          {activeTab === 'feature' && (
            <TemplateFeature templateId={templateId} />
          )}
          {activeTab === 'parameter' && (
            <TemplateParameter templateId={templateId} />
          )}
        </div>
      </Spin>

      {/* 工艺流程图组件 */}
      <ProcessFlowChart 
        templateId={templateId} 
        isOpen={flowChartVisible} 
        onClose={handleCloseFlowChart} 
      />
    </div>
  );
};

export default ProcessTemplateDetail; 